package my.jwds.p103;

import my.jwds.p94.TreeNode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class ZigzagLevelOrder {

    public static void main(String[] args) {
        ZigzagLevelOrder obj = new ZigzagLevelOrder();
        TreeNode node = TreeNode.to_binaryHaveNull(new Integer[]{1,2,3,4,null,null,5});
        System.out.println(obj.zigzagLevelOrder(node));
    }

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if (root == null)return new ArrayList<>();
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        List<List<Integer>> res = new ArrayList<>();
        while(!queue.isEmpty()){
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.removeFirst();
                list.add(node.val);
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null){
                    queue.add(node.right);
                }
            }
            res.add(list);
            if (res.size() % 2 == 0){
                Collections.reverse(list);
            }
        }
        return res;
    }
}